import { hsqj_input_common_GSDGB } from '../hsqj-input-common.js';
import { cwbbInput } from './options/cwbb.js';
import { getBaseInfo, backNationData } from '../message.js';

console.log('tax injected');
// 等待时间 timeout 时间
async function waitTimeOut(timeout = 1000) {
  return new Promise(function (resolve, reject) {
    setTimeout(() => {
      resolve();
    }, timeout);
  });
}

$(window).ready(function () {
  getBaseInfo()
});

window.addEventListener(
  'message',
  async function ({ data }) {
    // 只监听来自于content script的信息
    if (data.sender !== 'content-script') {
      return false;
    }
    if (data.event === 'setSaasData') {
      let sheet = data.data.saasData.sheet;
      let sheetType = data.data.saasData.sheetType;
      let type = data.data.baseInfo.taxInfo.institution;
      if (sheet === 'sds' || sheet === 'zzs') {
        // todo...
      } else if (sheetType.includes('hsqj')) {
        await hsqj_input_common_GSDGB(data.data, window.baseInfoCache);
      } else if (sheetType === 'cwbb') {
        await cwbbInput(sheet, type, data.data.saasData, window.baseInfoCache);
      }
    }
    if (data.event === 'getNationData') {
      getNationData(data.data.taxType);
    }

    if (data.event === 'getBaseInfo') {
      window.baseInfoCache = data.data;
      console.log('window.baseInfoCache ===', window.baseInfoCache);
      await autoInputAccount(window.baseInfoCache);
    }
  },
  false
);

async function autoInputAccount({ companyInfo }) {
  $('.header-login').click();
  await waitTimeOut(500);
  if ($('#Bullayer')) {
    $('#Bullayer').hide();
  }
  await waitTimeOut(500);
  $('.login-choice-shui').click();
  await waitTimeOut(500);
  const iframeEle = document.querySelector(
    'iframe[src="/etax/jsp/v2/login_bs.jsp"]'
  );
  let iframe = null;
  if (iframeEle) {
    iframe = iframeEle.contentWindow.document;
  }
  if (iframe) {
    // if (iframe.getElementsByClassName('login-phone')[0]) {
    //   iframe.getElementsByClassName('.')[0].click();
    //   await waitTimeOut(500);
    // }
    iframe.querySelector('.login-control > a:nth-child(3)').click();
    await waitTimeOut(500);

    companyInfo = companyInfo || {};
    iframe.querySelectorAll('#userName')[1].value =
      companyInfo.nationalTaxAccount || companyInfo.nationalTaxId;
    iframe.querySelectorAll('#passwdNsr')[1].value =
      companyInfo.nationalTaxPass;
  }
}

/**
 * 调用接口获取公司信息
 */
function getNationData(taxType) {
  let { institutionCode } = window.baseInfoCache.companyInfo;
  let taxInfo = {
    institution: institutionCode === '1' ? '2007' : '2013', // 国税对应制度 2007 | 2013
    // institution: '2007',
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
  };

  if (taxType.includes('hsqj') && institutionCode !== '1') {
    taxInfo.isHsqjSmall = true;
  }
  backNationData({
    taxInfo: taxInfo,
  })
}

function fillInput({ saasData, baseInfo }) {
  let message = '';
  if (saasData.data.type === 'file') {
    message = downloadFile(saasData.data.data, baseInfo);
  } else {
    message = '不支持json方式，下载文件失败！';
  }

  fillInputDone({
    message: message || '下载文件成功',
  })
}

/**
 * 下载文件
 * @param blob
 */
function downloadFile(blob, { taxInfo }) {
  blob = new Blob([blob], { type: 'text/xml' });
  let a = document.createElement('a');
  // 指定生成的文件名
  let name = `${taxInfo.nsrsbh}_${taxInfo.institution === '2013' ? 'ZL019' : 'ZL001'
    }`;
  const start = taxInfo.skssqq.replace(/-/g, '');
  const end = taxInfo.skssqz.replace(/-/g, '');
  a.download = `${name}_${start}_${end}.xml`;
  a.href = URL.createObjectURL(blob);
  document.body.appendChild(a);
  a.click();
}
